<?php

namespace Biz\model\activity;

use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Doraemon\model\Category as mCategory;
use Doraemon\pockets\datebase\BaseDbModel;

class CouponConfig extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_activity';

    const _DATABASE_ = 'shop_activity';

    const _TABLE_NAME = 'coupon_config';

    //是否参与返利
    const IS_REBATE_YES = 1;//参与返利
    const IS_REBATE_NO = 0;//不参与返利

    //优惠券类型
    const COUPON_TYPE_DISCOVER = 1;//满减
    const COUPON_TYPE_DISCOUNT = 2;//满折

    //渠道
    const COUPON_CHANNEL_APP = 1;//仅APP内
    const COUPON_CHANNEL_OUT_APP = 2;//仅APP外
    const COUPON_CHANNEL_THE_PARAGRAPH = 3;// 节选小程序


    //适用品类
    const CATE_SCOPE_ALL = 1;//全品类
    const CATE_SCOPE_NOT_ALL = 2;//部分品类
    const CATE_SCOPE_GOODS = 3;//商品
    const CATE_SCOPE_BRAND = 4;//品牌

    //承担方
    const COUPON_ASSUME_HHZ = 1;//好好住
    const COUPON_ASSUME_SHOP = 2;//商家专享


    //商家专属券限制的商品范围
    const GOODS_RANGE_ALL = 1;//全部商品
    const GOODS_RANGE_PART = 2;//部分指定商品

    //适用人群
    const PEOPLE_SCOPE_ALL = 1;//不限

    //是否与积分可用
    const COUPON_CAN_NOT_USE_WITH_INTEGRAL = 0;//不可与积分共用

    //领取规则
    const COUPON_RECEIVE_RULE_ONLY_ONE_PERSON = 1;//有个用户只能领取一次

    //有效期类型
    const TYPE_TIME_STATIC = 1;//固定期限
    const TYPE_TIME_RELATIVELY = 2;//相对期限

    //是否可领取
    const STATUS_CAN_RECEIVE = 1;//可领取 //需要配合展示时间是否可领取
//    const STATUS_WAIT_CONFIG = 0;//待配置
    const STATUS_CAN_NOT_RECEIVE = 2;//不可领 //关闭

    const NORMAL_COUPON_TYPE = 1;
    const BATCH_COUPON_TYPE = 2;

    const BELONGS_SH = 1;
    const BELONGS_BJ = 2;

    public static $belongs = [
        self::BELONGS_SH => '上海',
        self::BELONGS_BJ => '北京',
    ];

    public static $belongs_en = [
        self::BELONGS_SH => 'SH',
        self::BELONGS_BJ => 'BJ',
    ];

    public static $typeDesc = [
        self::COUPON_TYPE_DISCOVER => '满减',
        self::COUPON_TYPE_DISCOUNT => '满折',
    ];

    //渠道描述
    public static $channelDesc = [
        self::COUPON_CHANNEL_APP           => '仅APP内',
        self::COUPON_CHANNEL_OUT_APP       => '仅APP外',
        self::COUPON_CHANNEL_THE_PARAGRAPH => '节选小程序'
    ];

    //品类描述
    public static $cateScopeDesc = [
        self::CATE_SCOPE_ALL     => '全品类',
        self::CATE_SCOPE_NOT_ALL => '部分品类',
        self::CATE_SCOPE_GOODS   => '指定商品',
        self::CATE_SCOPE_BRAND   => '指定品牌'
    ];

    //承担方描述
    public static $assumeDesc = [
        self::COUPON_ASSUME_HHZ  => '好好住',
        self::COUPON_ASSUME_SHOP => '商家承担'
    ];


    //商家专属券的商品范围描述
    public static $goodsRangeDesc = [
        self::GOODS_RANGE_ALL  => '全部商品',
        self::GOODS_RANGE_PART => '部分商品'
    ];

    //期限类型描述
    public static $typeTimeDesc = [
        self::TYPE_TIME_STATIC     => '固定时间',
        self::TYPE_TIME_RELATIVELY => '根据领取时间计算'
    ];

    //领取规则描述
    public static $receiveRuleDesc = [
        self::COUPON_RECEIVE_RULE_ONLY_ONE_PERSON => '用户只能领取一次'
    ];

    //领取描述
    public static $receiveStatusDesc = [
        self::STATUS_CAN_RECEIVE     => '可领取',
        self::STATUS_CAN_NOT_RECEIVE => '不可领取',
        //        self::STATUS_WAIT_CONFIG     => '待配置'
    ];

    public static $peopleScopeDesc = [
        self::PEOPLE_SCOPE_ALL => '不限'
    ];


    //最大优惠券库存数量
    const MAX_TOTAL_COUNT = 100 * 10000;

    //最大设置的每人限领数
    const MAX_RECEIVE_PER_LIMIT = 1;

    //单张优惠券最多可以支持限制多少件商品
    const MAX_LIMIT_GOODS_NUM_PER = 100;


    public static function getByCouponCode($couponCode)
    {
        $where = ['coupon_code' => $couponCode];
        return self::get('*', $where);
    }

    public static function getByCouponCodes($couponCodes)
    {
        $where = ['coupon_code' => $couponCodes];
        return self::select('*', $where);
    }

    public static function create($data)
    {
        $data['addtime'] = date('Y-m-d H:i:s');
        $ret = self::insert($data);
        if ($ret->rowCount() == 0) {
            return false;
        }
        return self::id();
    }

    public static function setCannotReceive($couponId, $where = [])
    {
        self::update(['status' => self::STATUS_CAN_NOT_RECEIVE], array_merge(['coupon_id' => $couponId], $where));
    }

    public static function upData($id, $data)
    {
        $ret = self::update($data, ['coupon_id' => $id]);
        if ($ret->errorCode() !== '00000') {
            return false;
        }

        return true;
    }

    public static function getCount($where = [])
    {
        $idList = self::select('coupon_id', $where);
        if ($idList) {
            return count($idList);
        }
        return 0;
    }

    public static function getCouponList($where = [], $limit = [], $order = ['addtime' => 'DESC'], $fields = '*', $isFormat = true)
    {
        if ($limit) {
            $where['LIMIT'] = $limit;
        }

        $where['ORDER'] = $order;

        $result = self::select($fields, $where);
        $list = [];
        foreach ($result as $info) {

            if ($isFormat) self::formatInfo($info);

            $list[$info['coupon_id']] = $info;

        }
        if (empty($list)) {
            return [];
        }
        return $list;
    }

    public static function getCouponInfo($couponId, $fields = '*', $format = true)
    {
        $info = self::get($fields, ['coupon_id' => $couponId]);

        if (empty($info)) {
            return [];
        }

        if ($format) {
            self::formatInfo($info);
        }


        return $info;
    }

    //return false过期

    public static function checkExpired($startTime, $stopTime)
    {
        $nowTime = time();

        $startTime = strtotime($startTime);
        $stopTime = strtotime($stopTime);

        if ($startTime < 0 || $stopTime < 0) {
            return true;
        }

        if ($nowTime > $stopTime) {
            return false;
        }

        return true;
    }


    private static function formatInfo(&$info)
    {
        $nowDate = date('Y-m-d H:i:s');
        if ($info['start_show_time'] > $nowDate) {
            $info['status_desc'] = '未开始';
        } else if ($info['start_show_time'] < $nowDate && $info['stop_show_time'] > $nowDate) {
            $info['status_desc'] = '进行中';
        } else {
            $info['status_desc'] = '已结束';
        }
        foreach ($info as $key => $value) {
            switch ($key) {
                case 'type':
                    $info['type_desc'] = isset(self::$typeDesc[$value]) ? self::$typeDesc[$value] : '';
                    break;
                case 'channel':
                    $info['channel_desc'] = isset(self::$channelDesc[$value]) ? self::$channelDesc[$value] : '';
                    break;
                case 'cate_scope':
                    $info['cate_scope_desc'] = isset(self::$cateScopeDesc[$value]) ? self::$cateScopeDesc[$value] : '';

                    if ($value == self::CATE_SCOPE_NOT_ALL && !empty($info['cate_ids'])) {
                        $info['cate_ids'] = self::parseCateIds($info['cate_ids']);
                    }
                    break;
                case 'assume':
                    $info['assume_desc'] = isset(self::$assumeDesc[$value]) ? self::$assumeDesc[$value] : '';
                    break;
                case 'goods_range':
                    $info['goods_range_desc'] = isset(self::$goodsRangeDesc[$value]) ? self::$goodsRangeDesc[$value] : '';
                    break;
                case 'people_scope':
                    $info['people_scope_desc'] = isset(self::$peopleScopeDesc[$value]) ? self::$peopleScopeDesc[$value] : '';
                    break;
                case 'receive_rule':
                    $info['receive_rule_desc'] = isset(self::$receiveRuleDesc[$value]) ? self::$receiveRuleDesc[$value] : '';
                    break;
                case 'type_time':
                    if ($value == self::TYPE_TIME_STATIC) {
                        $info['time_desc'] = substr($info['start_time'], 0, 10) . '至' . substr($info['stop_time'], 0, 10);
                    }

                    if ($value == self::TYPE_TIME_RELATIVELY) {
                        $info['time_desc'] = sprintf('领取后%s天有效', $info['relative_days']);
                    }
                    break;
//                case 'status':
//                    $info['status_desc'] = isset(self::$receiveStatusDesc[$value]) ? self::$receiveStatusDesc[$value] : '';
//                    break;
                case 'include_goods_ids':
                    if (!empty($value)) {
                        $goodsIds = array_filter(explode(',', $value));

                        $goodsList = mGoodsBasicInfo::getInfoList($goodsIds, [
                            'goods_id',
                            'spec_img'
                        ]);

                        $info['include_goods_list'] = array_values($goodsList);
                    }
                    break;

            }
        }
    }


    public static function getCloudTags()
    {
        $list = self::select([
            'title',
            'addtime'
        ], [
            'shop_id'   => 0,
            'status[!]' => self::STATUS_CAN_NOT_RECEIVE,
            'GROUP'     => 'title',
            'ORDER'     => ['coupon_id' => 'DESC']
        ]);

        $result = [];

        if (empty($list)) {
            return $result;
        }

        //上周的时间点
        $prevWeekStart = strtotime(date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1 - 7, date("Y"))));
        $prevWeekStop = strtotime(date("Y-m-d H:i:s", mktime(23, 59, 59, date("m"), date("d") - date("w") + 7 - 7, date("Y"))));

        //本周时间点
        $nowWeekStart = strtotime(date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y"))));
        $nowWeekStop = strtotime(date("Y-m-d H:i:s", mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y"))));


        array_map(function ($v) use (&$result, $prevWeekStart, $prevWeekStop, $nowWeekStart, $nowWeekStop) {
            $addTimeStamp = strtotime($v['addtime']);
            $timeTag = substr($v['addtime'], 0, 10);

            if ($addTimeStamp >= $prevWeekStart && $addTimeStamp <= $prevWeekStop) {
                $timeTag = '上周';
            } elseif ($addTimeStamp >= $nowWeekStart && $addTimeStamp <= $nowWeekStop) {
                $timeTag = '本周';
            }

            $result[$timeTag][] = $v['title'];
        }, $list);

        return $result;
    }

    /**
     * @desc 查询优惠券领取情况
     * @param mixed $coupon_ids 优惠券id
     * @return mixed
     * @throws \Exception
     */
    public static function getCouponReceived($coupon_ids)
    {
        $list = self::select([
            'coupon_id',
            'total_count',
            'received_count'
        ],
            ['coupon_id' => $coupon_ids]
        );
        return $list;
    }

    public static function parseCateIds($cateIds = '')
    {
        $result = [];
        if (!empty($cateIds)) {
            $cateIds = trim($cateIds, '|');
            $cateIds = explode('|', $cateIds);

            array_map(function ($v) use (&$result) {
                list($pid, $cateId) = explode('-', $v);
                $result["i{$pid}"][] = $cateId;
            }, $cateIds);
        }

        return $result;
    }

    public static function buildAdmSaveCateIds($catePIds = [], $cateIds = [])
    {
        $data = [];
        $ret = '';

        if (!empty($catePIds)) {
            array_map(function ($v) use (&$data) {
                if ($v == 0) {
                    return;
                }
                $data[$v . '-0'] = $v . '-0';
            }, $catePIds);
        }

        if (!empty($cateIds)) {
            foreach ($cateIds as $pid => $cates) {
                if (isset($data[$pid . '-0'])) {
                    continue;
                }

                if (is_array($cates)) {
                    array_map(function ($v) use (&$data, $pid) {
                        if ($v == 0) {
                            return;
                        }
                        $data[$pid . '-' . $v] = $pid . '-' . $v;
                    }, $cates);
                } else {
                    $data[$pid . '-' . $cates] = $pid . '-' . $cates;
                }
            }
        }

        if (!empty($data)) {
            $ret = sprintf("|%s|", implode('|', $data));
        }

        return $ret;
    }

    public static function cateIdsDesc($cateIds = '')
    {
        $cateIds = self::parseCateIds($cateIds);
        $data = [];

        if (empty($cateIds)) {
            return '';
        }

        foreach ($cateIds as $pid => $cates) {
            $cateNum = count($cates);

            if ($cateNum == 1) {
                if (in_array(0, $cates)) {
                    $data[] = ltrim($pid, 'i');
                } else {
                    $data[] = $cates[0];
                }
            } else {
                $data[] = ltrim($pid, 'i');
            }
        }

        if (!empty($data)) {
            $cateInfos = mCategory::selectCategorys($data);

            $data = array_column($cateInfos, 'cate_name');
        }

        return implode(',', $data);

    }

    public static function createRebateCoupon($couponCodes, $is_create = true, $params = '', $coupon = '')
    {
        $res = [];
        $data = [];
        $data['title'] = $is_create ? '设计师券' : '设计师单次券';
        $data['assume'] = self::COUPON_ASSUME_HHZ;
        $data['belongs'] = isset($params['belongs']) ? $params['belongs'] : '';
        //暂时一个返利优惠码可以生成10万张
        $data['total_count'] = $is_create ? 100000 : 1;
        $data['channel'] = self::COUPON_CHANNEL_THE_PARAGRAPH;
        $data['cate_scope'] = self::CATE_SCOPE_ALL;
        $data['receive_rule'] = 0;

        $data['type'] = self::COUPON_TYPE_DISCOUNT;
        $data['full_amount'] = $is_create ? 1 : $coupon['full_amount'];
        $data['discount_level'] = $is_create ? 9.5 : $coupon['discount_level'];

        $data['type_time'] = self::TYPE_TIME_STATIC;
        $data['start_time'] = $is_create ? date('Y-m-d H:i:s') : $coupon['start_time'];
        $data['stop_time'] = $is_create ? date('Y-m-d H:i:s', time() + 315360000) : $coupon['stop_time'];
        $data['start_show_time'] = $data['start_time'];
        $data['stop_show_time'] = $data['stop_time'];

        $data['status'] = $is_create ? self::STATUS_CAN_NOT_RECEIVE : ($coupon['status'] ? self::STATUS_CAN_RECEIVE : self::STATUS_CAN_NOT_RECEIVE);

        foreach ($couponCodes as $couponCode) {
            $data['coupon_code'] = $couponCode;
            $id = self::create($data);

            $res[$couponCode] = $id;
        }

        return $res;


    }

    public static function createAppCouponCode($couponInfo)
    {
        $formatCouponInfo = [
            'title'           => "我要带货-{$couponInfo['uid']}",
            'assume'          => self::COUPON_ASSUME_HHZ,
            'belongs'         => '',
            'total_count'     => 100000,
            'channel'         => self::COUPON_CHANNEL_APP,
            'cate_scope'      => $couponInfo['cate_scope'],
            'receive_rule'    => 0,
            'type'            => self::COUPON_TYPE_DISCOVER,
            'full_amount'     => $couponInfo['full_amount'],
            'include_goods_ids'     => $couponInfo['include_goods_ids'],
            'detract_amount'  => $couponInfo['detract_amount'],
            'type_time'       => self::TYPE_TIME_STATIC,
            'start_time'      => $couponInfo['start_time'],
            'stop_time'       => $couponInfo['stop_time'],
            'start_show_time' => $couponInfo['start_time'],
            'stop_show_time'  => $couponInfo['stop_time'],
            'goods_range'     => $couponInfo['goods_range'],
            'status'          => self::STATUS_CAN_RECEIVE,
            'coupon_code'     => $couponInfo['coupon_code']
        ];
        return self::create($formatCouponInfo);
    }


}